package cn.ava.system.service.impl;

import cn.ava.system.domain.Role;
import cn.ava.system.mapper.RoleMapper;
import cn.ava.system.service.IRoleService;
import cn.ava.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ava
 * @since 2022-07-11
 */
@Service
// 开启事务 只读属性和支持事务
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * @Title: add
     * @Description: 重写添加方法,初始化关联表
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/13 18:11
     * @param:
     * @return:
     */
    @Override
    @Transactional
    public void add(Role role) {
        // 保存
        roleMapper.add(role);
        // 初始化中间表
        initRelationTable(role);
    }


    /**
     * @Title: initRelationTable
     * @Description: 初始化关联表
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/13 18:12
     * @param:
     * @return:
     */
    public void initRelationTable(Role role) {
        // 删除对应菜单表
        roleMapper.deleteRoleMenu(role.getId());
        // 删除对应权限表
        roleMapper.deleteRolePermission(role.getId());
        // 添加对应菜单表
        roleMapper.addRoleMenu(role.getId(),role.getMenus());
        // 添加对应权限表
        roleMapper.addRolePermission(role.getId(),role.getPermissions());
    }


    @Override
    @Transactional
    public void update(Role role) {
        // 修改数据
        roleMapper.update(role);
        // 同步修改
        initRelationTable(role);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 获取到对应的数据
        Role role = roleMapper.getById(id);
        // 主键id
        Long rId = role.getId();
        // 根据id删除
        roleMapper.deleteRoleMenu(rId);
        roleMapper.deleteRolePermission(rId);
        roleMapper.delete(id);

    }
}
